param
(
	[parameter(Mandatory=$true, Position=0)]
	[string] $TargetUrl
)

$currentDir = $location = Get-Location -PSProvider FileSystem
$location = $currentDir.Path  + "\..\WSP"
$solutionName = "TemplateLibraryConnector.wsp"
$sol = Get-SPSolution | Where-Object {$_.Name -eq $solutionName}
$WebApp = Get-SPWebApplication $TargetUrl

Write-Host " "
if($sol -eq $null)
{
	Add-SPSolution $location\$solutionName
	write-host "Adding $($solutionName) ..." -NoNewline
	do 
	{ 
		Write-Host "." -NoNewline
		Start-Sleep 1
	}
	while ((Get-SPSolution $solutionName).JobExists -eq $true)
	Write-Host "ok"
}
else
{
	Write-Host "Solution $($solutionName) already added to solution store"
}

$sol = Get-SPSolution | Where-Object {$_.Name -eq $solutionName}
if ($sol -ne $null) {
	if($sol.DeployedWebApplications.Contains($WebApp) -eq $false)
	{	
		Install-SPSolution -Identity $solutionName -WebApplication $TargetUrl -GACDeployment
		write-host "Installing $($solutionName) to $TargetUrl" -NoNewline
		do 
		{ 
			Write-Host "." -NoNewline
			Start-Sleep 1
		}
		while ((Get-SPSolution $solutionName).JobExists -eq $true)
		Write-Host "ok"
	}
	else
	{
		Write-Host "Solution $($solutionName) already deployed."
		Write-Host "Upgrading $TargetUrl" -NoNewLine
		Update-SPSolution -Identity $solutionName -LiteralPath $location\$solutionName -GACDeployment -CASPolicies -Force
		do 
		{ 
			Write-Host "." -NoNewline
			Start-Sleep 1
		}
		while ((Get-SPSolution $solutionName).JobExists -eq $true)
		Write-Host "ok"
	}
}
else
{
	Write-Host "Solution $($solutionName) was not installed, cannot deploy."
}
Write-Host " "
Write-Host "*** Installation finished ***"
Write-Host " "
Write-Host "Please enable the Template Library Connector on a site collection:"
Write-Host "-in the GUI (Site Actions -> Site settings -> Site collection features)"
Write-Host "-or Enable-SPFeature TemplateLibraryConnector -Url http://server/sites/sitename"
Write-Host " "
Write-Host "To designate a site collection as a template hub, run .\definehub.ps1"
Write-Host " "